﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using HZY.Repository.Core.Models;
using HZY.Toolkit;
using HZY.Toolkit.Attributes;
using Microsoft.AspNetCore.Http;
using NPOI.HSSF.UserModel;

namespace HZY.Framework.Services
{
    [AppService]
    public class AdminBaseService<TRepository> : FrameworkBaseService<TRepository> where TRepository : class
    {
        public AdminBaseService(TRepository repository) : base(repository)
        {
        }

        #region 导出 Excel

        /// <summary>
        /// 导出 Excel
        /// </summary>
        /// <param name="pagingViewModel"></param>
        /// <param name="byName">别名</param>
        /// <returns></returns>
        protected virtual byte[] ExportExcelByPagingViewModel(PagingViewModel pagingViewModel,
            Dictionary<string, string> byName = null)
        {
            var workbook = new HSSFWorkbook();
            var sheet = workbook.CreateSheet();
            //数据
            var data = pagingViewModel.Result;
            var cols = pagingViewModel.Columns.Where(w => w.Show).ToList();
            //填充表头
            var dataRow = sheet.CreateRow(0);
            foreach (var item in cols)
            {
                var index = cols.IndexOf(item);
                if (byName != null && byName.ContainsKey(item.FieldName))
                {
                    dataRow.CreateCell(index).SetCellValue(byName[item.FieldName]);
                }
                else
                {
                    dataRow.CreateCell(index).SetCellValue(item.Title);
                }
            }

            //填充内容
            for (var i = 0; i < data.Count; i++)
            {
                var item = data[i];
                dataRow = sheet.CreateRow(i + 1);
                foreach (var col in cols)
                {
                    if (!col.Show) continue;
                    var index = cols.IndexOf(col);
                    var name = col.FieldName.FirstCharToUpper();
                    if (!item.ContainsKey(name)) continue;
                    var value = item[name];
                    dataRow.CreateCell(index).SetCellValue(value == null ? "" : value.ToString());
                }
            }

            //填充byte
            using var ms = new MemoryStream();
            workbook.Write(ms);
            return ms.ToArray();
        }

        #endregion

        #region 上传文件

        /// <summary>
        /// 上传文件 辅助函数
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="webRootPath"></param>
        /// <param name="folder"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        protected virtual string HandleUploadFile(IFormFile formFile, string webRootPath, string folder,
            params string[] format)
        {
            var extensionName = Path.GetExtension(formFile.FileName)?.ToLower().Trim(); //获取后缀名

            if (format != null && format.Length > 0 && !format.ToList().Contains(extensionName.ToLower()))
            {
                throw new MessageBox("请上传后缀名为：" + string.Join("、", format) + " 格式的文件");
            }

            if (string.IsNullOrWhiteSpace(folder)) folder = "files";

            var path = $"/upload/{folder}";

            if (!Directory.Exists(webRootPath + path))
            {
                Directory.CreateDirectory(webRootPath + path);
            }

            path += $"/{DateTime.Now:yyyyMMdd}";

            if (!Directory.Exists(webRootPath + path))
            {
                Directory.CreateDirectory(webRootPath + path);
            }

            path += $"/time_{DateTime.Now:HHmmss}_old_name_{formFile.FileName}";

            // 创建新文件
            using var fs = File.Create(webRootPath + path);
            formFile.CopyTo(fs);
            // 清空缓冲区数据
            fs.Flush();

            return path;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="iFormFile"></param>
        /// <param name="webRootPath"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        protected virtual string HandleUploadFile(IFormFile iFormFile, string webRootPath, params string[] format)
            => this.HandleUploadFile(iFormFile, webRootPath, "files", format);

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="iFormFile"></param>
        /// <param name="webRootPath"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        protected virtual string HandleUploadImageFile(IFormFile iFormFile, string webRootPath, string folder = "files")
            => this.HandleUploadFile(iFormFile, webRootPath, folder, ".jpg", ".jpeg", ".png", ".gif", ".jfif");

        #endregion
    }
}